<template>
    <a-card>
        <div>
            <a-form layout="horizontal">
                <div class="fold">
                    <a-row>
                        <a-col :md="6" :sm="24">
                            <a-form-item label="入库单号" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                                <a-input v-model="docNum" placeholder="请输入" allowClear />
                            </a-form-item>
                        </a-col>
                        <a-col :md="6" :sm="24">
                            <a-form-item label="标签" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                                <a-input v-model="labelId" placeholder="请输入" allowClear />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </div>
                <span style="float: right; margin-top: 3px">
                    <a-button type="primary" @click="query">查询</a-button>
                    <a-button @click="exportExcel" style="margin-left: 10px" :loading="logging">导出</a-button>
                </span>
            </a-form>
        </div>
        <div>
            <a-space class="operator">
                <a-button @click="showModal()" type="primary">Agv呼叫</a-button>
                <a-button @click="batchComplete">批量手动完结</a-button>
            </a-space>
            <a-table :columns="columns" :dataSource="dataSource" :pagination="pagination" @change="paginationChange"
                :rowSelection="rowSelection" :scroll="{ y: 500 }" :rowKey="(dataSource) => dataSource.Id"
                :expandedRowKeys="expandedRowKeys">

                <template slot="time" slot-scope="text, record">
                    {{ record.CreateTime | dateTimeFormat }}
                </template>

                <template slot="docType" slot-scope="text">
                    <a-tag :color="text == 'R-001' ? 'green' : text == 'R-002' ? 'red' : 'geekblue'">
                        {{ docTypeList.find(i => i.key == text).value }}
                    </a-tag>
                </template>
                <template slot="ellipsis" slot-scope="text">
                    <a-tooltip placement="bottom" :title="text">
                        {{ text.length > 20 ? text.substring(0, 20) + '...' : text }}
                    </a-tooltip>
                </template>
                <template slot="ellipsis2" slot-scope="text">
                    <a-tooltip placement="bottom" :title="text">
                        {{ text.length > 10 ? text.substring(0, 10) + '...' : text }}
                    </a-tooltip>
                </template>
            </a-table>

            <a-modal :visible="visible" title="Agv呼叫" @cancel="handleCancel" width="600px">
                <a-form>
                    <a-row>
                        <a-col :span="24">
                            <a-form-item :label-col="layout.labelCol" :wrapper-col="layout.wrapperCol" label="位置">
                                <a-radio-group v-model="model.From">
                                    <a-radio :value="item.Code" v-for="item in positionList" :key="item.Code">
                                        {{ item.Code + '（' + item.PodCode + '）' }}
                                    </a-radio>
                                </a-radio-group>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>

                <template slot="footer">
                    <a-button class="ant-btn-primary" @click="agvCall">Agv呼叫</a-button>
                </template>
            </a-modal>
        </div>
    </a-card>
</template>
  
<script>
import { orderService, agvServoce, agvPointMapService } from '/src/services'
import moment from 'moment'
import ExportJsonExcel from "js-export-excel"

const columns = [
    {
        title: '序号',
        width: 60,
        customRender: (text, record, index) => `${index + 1}`,
    },
    {
        title: '单号',
        width: 130,
        dataIndex: 'DocNum'
    },
    {
        title: '供应商',
        width: 120,
        dataIndex: 'SupplierName'
    },
    {
        title: '标签',
        width: 270,
        dataIndex: 'LabelId'
    },
    {
        title: '物料名称',
        width: 180,
        dataIndex: 'ItemName',
        scopedSlots: { customRender: 'ellipsis' }
    },
    {
        title: '原厂料号',
        width: 170,
        dataIndex: 'PartNo',
        scopedSlots: { customRender: 'ellipsis' }
    },
    {
        title: '数量',
        width: 70,
        dataIndex: 'PlanQty'
    },
    {
        title: '贴标数量',
        width: 80,
        dataIndex: 'LabelQty'
    },
    {
        title: '创建时间',
        width: 180,
        dataIndex: 'CreateTime',
        scopedSlots: { customRender: 'time' }
    }
]

export default {
    name: 'DataLogReport',
    filters: {
        dateTimeFormat(val) {
            if (val == null) return ''
            return val.replace('T', ' ').substring(0, 19)
        }
    },
    data() {
        return {
            layout: {
                labelCol: { span: 6 },
                wrapperCol: { span: 16 }
            },
            columns: columns,
            dataSource: [],
            expandedRowKeys: [],
            itemDataSource: [],
            type: '',
            docType: '',
            status: '',
            docNum: '',
            labelId: '',
            supplierCode: '',
            docTypeList: [
                { key: 'R-001', value: '到货入库' },
                { key: 'R-002', value: '退料入库' },
            ],
            date: moment(),
            pagination: {
                total: 0,
                current: 1,
                pageSize: 20,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '50', '100'],
                showTotal: (total) => `总计 ${total} 条`,
                onChange: (current, pageSize) => {
                    this.pagination.pageSize = pageSize
                    this.pagination.current = current
                    this.loadData()
                }
            },
            selectedRowKeys: [],
            pageIndex: 1,
            pageSize: 15,
            logging: false,
            model: {
                DocNum: '',
                LabelId: '',
                From: '',
                IsSevenInch: true
            },
            docNums: [],
            pickDataSource: [],
            tempPickDataSource: [],
            pickColumns: [
                {
                    title: '序号',
                    width: 60,
                    customRender: (text, record, index) => `${index + 1}`,
                },
                {
                    title: '标签',
                    width: 270,
                    dataIndex: 'LabelId'
                },
                {
                    title: '物料编码',
                    width: 150,
                    dataIndex: 'ItemCode'
                },
                {
                    title: '物料名称',
                    width: 150,
                    dataIndex: 'ItemName'
                },
                {
                    title: '供应商',
                    width: 150,
                    dataIndex: 'SupplierName'
                },
                {
                    title: '规格',
                    width: 80,
                    customRender: (text, record) => record.IsSevenInch ? '七寸' : '非七寸'
                },
                {
                    title: '状态',
                    width: 80,
                    dataIndex: 'Status',
                    scopedSlots: { customRender: 'status' }
                },
                {
                    title: '操作',
                    width: 80,
                    scopedSlots: { customRender: 'action' }
                }
            ],
            statusList: [
                { key: 0, value: '等待贴标' },
                { key: 1, value: '贴标完成' },
                { key: 2, value: '入库中' },
                { key: 3, value: '入库完成' },
                { key: -1, value: '删除' },
                { key: -2, value: '入库失败' },
                { key: -3, value: '贴标失败' },
                { key: -4, value: '贴标撤销' },
            ],
            positionList: [],
            visible: false,
        }
    },
    created() {
        document.body.addEventListener("keyup", (e) => {
            if (window.event) {
                e = window.event
            }
            let code = e.charCode || e.keyCode
            if (code === 13) {
                this.handleOk()
            }
        })
    },
    mounted: function () {
        this.loadData()
    },
    computed: {
        rowSelection() {
            const { selectedRowKeys } = this
            return {
                selectedRowKeys,
                onChange: this.onSelectChange,
                getCheckboxProps: (record) => ({
                    props: {
                        disabled: record.Status != 0,
                    },
                }),
            }
        },
    },
    methods: {
        async paginationChange(pagination) {
            this.pagination.pageSize = pagination.pageSize
            this.pagination.current = pagination.current
            this.loadData()
        },
        async loadData() {
            var result = await orderService.getReturnItemData(this.docNum, this.labelId, this.pagination.pageSize, this.pagination.current)
            if (result && result.data) {
                this.dataSource = result.data.data
                this.pagination.total = result.data.total
            }
        },
        query() {
            this.pagination.current = 1
            this.loadData()
        },
        async exportExcel() {
            this.logging = true;
            var result = await orderService.getItemData(0, this.docNum, this.supplierCode, 10000, 1)

            if (result && result.data) {
                var option = {};
                let dataTable = [];
                let datas = result.data.data;

                datas.forEach(item => {
                    item.CreateTime = (item.UpdateTime ? item.UpdateTime : item.CreateTime).replace('T', ' ').substring(0, 19)
                    item.DocType = this.docTypeList.find(i => i.key == item.DocType).value;
                    dataTable.push(item);
                });
                var sheetFilter = [];
                var sheetHeader = [];
                columns.forEach(item => {
                    if (item.title !== "序号" && item.title !== "操作") {
                        sheetFilter.push(item.dataIndex)
                        sheetHeader.push(item.title)
                    }
                })
                option.fileName = this.$route.name + '_' + moment().format('YYYY-MM-DD');
                option.datas = [
                    {
                        sheetData: dataTable,
                        sheetName: 'sheet',
                        sheetFilter: sheetFilter,
                        sheetHeader: sheetHeader,
                    }
                ];
                var toExcel = new ExportJsonExcel(option);
                toExcel.saveExcel();
                this.logging = false;
            }

        },
        async getInnerData(expanded, record) {
            this.expandedRowKeys = []
            this.itemDataSource = []
            if (expanded) {
                this.expandedRowKeys.push(record.Id)
                this.inndata = [];
                var result = await orderService.getItems(record.DocNum)
                if (result && result.data) {
                    this.itemDataSource = result.data
                }
            }
        },
        async showModal() {
            this.visible = true
            this.model.LabelId = '';
            if (this.docNums.length == 0) {
                this.getTLOrderNum();
            }
            // this.model.DocNum = docNum
            this.getPostion();
        },
        async getPostion() {
            let result = await agvPointMapService.getFrom()
            if (result && result.data) {
                this.positionList = result.data;
                if (result.data.length == 0) {
                    this.visible = false
                    this.$message.error('收料区没有工装')
                    return false;
                }
            }
        },
        async getTLOrderNum() {
            let result = await orderService.getTLOrderNum()
            if (result && result.data) {
                this.docNums = result.data;
            }
        },
        async initPickData() {
            let result = await orderService.getPickOrderDetail(this.model.DocNum)
            this.tempPickDataSource = result.data;
            this.pickDataSource = this.tempPickDataSource.filter(i => i.IsSevenInch == this.model.IsSevenInch)
        },
        changeSwitch() {
            this.pickDataSource = this.tempPickDataSource.filter(i => i.IsSevenInch == this.model.IsSevenInch)
        },
        async handleOk() {
            if (!this.visible) return false;
            if (!this.model.LabelId) {
                this.$message.error('请输入标签')
                return false;
            }
            if (this.pickDataSource.find(i => i.LabelId == this.model.LabelId)) {
                this.$message.error('请勿重复录入')
                return false;
            }
            var res = await orderService.pickReturnOrder(this.model)

            if (res && res.data) {
                this.$message.success('拣货成功')
                this.model.LabelId = ''
                this.initPickData()
            } else {
                this.$message.error('拣货失败，物料信息不存在')
            }
        },
        handleCancel() {
            this.visible = false
        },
        async remove(labelId) {
            var data = {
                DocNum: this.model.DocNum,
                LabelId: labelId,
                IsRemove: true
            }
            let result = await orderService.removePick(data)
            if (result.data) {
                this.$message.success("移除成功", 3)
                this.initPickData()
            }
        },
        async agvCall() {
            if (!this.model.From) {
                this.$message.error("请选择点位", 3)
                return;
            }
            var result = await agvServoce.toDLJ(this.model.From);
            if (result.data.Code == 0) {
                this.$message.success("呼叫成功", 3)
            } else {
                this.$message.error(result.data.Message)
            }
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys;
        },
        async completeTask(id) {
            console.log(id)
        },
        async batchComplete() {
            if (this.selectedRowKeys.length === 0) {
                this.$message.error("请勾选至少一条数据", 3)
            }
            console.log(this.selectedRowKeys.join(','))
            let result = await orderService.batchCompleteTask(this.selectedRowKeys.join(','))
            if (result && result.data) {
                if (result.data.Code != 0) {
                    this.$message.error(result.data.Message)
                    return;
                }
                this.$message.success("操作成功", 3)
                this.loadData()
            }
        }
    }
}
</script>
  
<style lang="less">
.fold {
    width: calc(100% - 216px);
    display: inline-block;
}

.ant-input-number-handler-wrap {
    display: none
}

.ant-table-tbody .ant-table-row-cell-break-word {
    word-break: break-all;
}

.drawer.right {
    top: 0;
}
</style>
  
  